package com.example.oauth2.config.exception;

import cn.hutool.core.util.ArrayUtil;
import com.example.oauth2.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 全局异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(HttpServletRequest request, Exception e) {
        if (e != null) {
            StackTraceElement[] stackTrace = e.getStackTrace();
            if (ArrayUtil.isNotEmpty(stackTrace)) {
                log.error("报错接口：{}", request.getRequestURI(), e);
            }
        }
        return Result.fail("服务器异常，请联系客服或稍后重试！");
    }

    /**
     * 统一参数校验
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleBindException(MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.info("参数校验异常:{}({})", fieldError.getDefaultMessage(), fieldError.getField());
        return Result.fail(fieldError.getDefaultMessage());
    }

    /**
     * 统一参数校验
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result handleBindException(BindException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.info("参数校验异常:{}({})", fieldError.getDefaultMessage(), fieldError.getField());
        return Result.fail(fieldError.getDefaultMessage());
    }

    /**
     * 自定义异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ApplicationException.class)
    public Result ApplicationException(ApplicationException e) {
        return Result.fail(e.getMessage());
    }
}
